<template>
  <div v-loading.lock="loading" element-loading-text="插入中,请稍候">
    <div ref="editor"></div>
  </div>
</template>

<script>
import { loadRemote, config, assign } from '@vimi/utils-tool'
import { Message } from 'element-ui'
import { uploadOss } from '@/common/api/oss'

const editorCdn = `${config.baseUrl}/libs/wang-editor/4.6.16/wangEditor.js`
const golbalVar = 'wangEditor'

const defaultConfig = {
  height: 500,
  zIndex: 2000,
  menuTooltipPosition: 'down',
  onchangeTimeout: 600,
  showLinkImgAlt: false,
  showLinkImgHref: false,
  pasteIgnoreImg: true,
  menus: [
    'head',
    'bold',
    'fontSize',
    'fontName',
    'italic',
    'underline',
    'strikeThrough',
    'indent',
    'lineHeight',
    'foreColor',
    'backColor',
    'link',
    'list',
    'todo',
    'justify',
    // 'quote',
    // 'emoticon',
    'image',
    'video',
    'table',
    // 'code',
    'splitLine',
    'undo',
    'redo',
  ],
  customAlert: (s, t) => {
    switch (t) {
      case 'success':
        Message.success(s)
        break
      case 'info':
        Message.info(s)
        break
      case 'warning':
        Message.warning(s)
        break
      case 'error':
        Message.error(s)
        break
      default:
        Message.info(s)
        break
    }
  },
  pasteTextHandle: pasteStr => {
    return pasteStr.replace(/<table>/g, '<table class="table">')
  },
}

export default {
  components: {},
  props: {
    config: {
      type: Object,
      default: () => ({}),
    },
    value: String,
    disabled: Boolean,
    dir: {
      type: String,
      default: 'weditor_file',
    },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
  data() {
    return {
      editor: null,
      loading: false,
      hasInit: false,
      changing: false,
    }
  },
  computed: {},
  watch: {
    value(val) {
      if (!this.changing) {
        this.changing = false
        this.setHtml(val)
      }
    },
    disabled(val) {
      this.toggleDisable(val)
    },
  },
  created() {
    this.loadEditor()
  },
  mounted() {},
  beforeDestroy() {
    if (this.editor) {
      this.editor.destroy()
      this.editor = null
    }
  },
  methods: {
    async loadEditor() {
      await loadRemote(editorCdn, golbalVar)
      this.initEditor()
    },

    initEditor() {
      const editorRef = this.$refs.editor
      if (!editorRef) return

      const E = window[golbalVar]
      this.editor = new E(editorRef)
      this.editor.config = assign(
        this.editor.config,
        defaultConfig,
        {
          onchange: newHtml => {
            // init完成后第一次setHtml，changing要设置为false，其余为true
            this.changing = this.hasInit
            this.hasInit = true
            this.$emit('change', newHtml)
          },
          onblur: newHtml => {
            this.$emit('blur', newHtml)
          },
          onfocus: newHtml => {
            this.$emit('focus', newHtml)
          },
          customUploadImg: (resultFiles, insertImgFn) => {
            Promise.all(
              resultFiles.map(file =>
                uploadOss({
                  file,
                  dir: this.dir,
                })
              )
            )
              .then(list => {
                list.forEach(url => insertImgFn(url))
              })
              .catch(() => {
                this.$message.error('插入图片失败，请重试！')
              })
          },
        },
        this.config
      )

      this.editor.create()
      this.setHtml(this.value)
      this.toggleDisable(this.disabled)

      this.$emit('ready', this.editor)
    },

    setHtml(val) {
      return this.editor?.txt?.html?.(val)
    },

    toggleDisable(val) {
      return val ? this.editor?.disable() : this.editor?.enable()
    },
  },
}
</script>

<style lang="scss" scoped></style>
